package com.wjy.demo.service;

import com.wjy.demo.dao.UserInfoDao;
import com.wjy.demo.entity.UserInfo;
import com.wjy.demo.error.ErrorType;
import com.wjy.demo.error.ServiceException;
import com.wjy.demo.utils.CommBeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
public class UserService {

    @Autowired
    HttpServletRequest request;

    @Autowired
    private UserInfoDao userInfoDao;



//    public List<UserInfo> userList() {
//        return userInfoDao.queryAll();
//    }

    public Integer insert(UserInfo userInfo) {

        String openId = userInfo.getOpenId();

        if (StringUtils.isBlank(openId)) {
            openId = request.getHeader("X-WX-OPENID");
        }

        if (StringUtils.isBlank(openId)) {
            throw new ServiceException(ErrorType.OPEN_ID_IS_NULL);
        }

        UserInfo userInfoInDB = userInfoDao.queryByOpenId(openId);
        if (null != userInfoInDB) {
            throw new ServiceException(ErrorType.USER_EXIST);
        }

        UserInfo temp = new UserInfo();
        CommBeanUtils.copyProperties(userInfo, temp);
        temp.setOpenId(openId);
        Long now = System.currentTimeMillis();
        userInfo.setCreateTime(now);
        userInfo.setUpdateTime(now);
        return userInfoDao.insert(temp);
    }


    public Integer update(UserInfo userInfo) {
        Long id = userInfo.getId();
        if (Objects.isNull(id)) {
            throw new ServiceException(ErrorType.OPEN_ID_IS_NULL);
        }

        UserInfo userInfoInDB = userInfoDao.queryById(id);
        if (null == userInfoInDB) {
            throw new ServiceException(ErrorType.USER_NOT_EXIST);
        }

        Long now = System.currentTimeMillis();
        UserInfo userTemp = new UserInfo();
        CommBeanUtils.copyProperties(userInfoInDB, userTemp);
        userTemp.setUpdateTime(now);
        return userInfoDao.update(userTemp);
    }

    //public UserInfo queryByTelephone(String telephone){return userInfoDao.queryByTelephone(telephone);}
    public UserInfo queryById(Long id) {
        return userInfoDao.queryById(id);
    }

    public UserInfo queryByOpenId(String openId) {
        if (StringUtils.isEmpty(openId)) {
            openId = request.getHeader("X-WX-OPENID");
        }

        if (null != null) {
            throw new ServiceException(ErrorType.OPEN_ID_IS_NULL);
        }

        return userInfoDao.queryByOpenId(openId);
    }


}
